from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit, QPushButton, QHBoxLayout, QVBoxLayout, QTableWidget, QMessageBox
from utils.httpUtil import RequestUtil
from utils.memoryUtil import PandasSharedMemory
from components.paged_table import PagedTable
import pandas as pd
from PyQt5 import QtCore
from components.form_dialog import FormDialog

column_name = ['id', '菜谱类型id', '类型名称', '菜谱名称', '做法', '特性', '提示', '调料', '原料']

class CookBook(QWidget):
    """
    调用聚合数据的菜谱接口，获取菜谱，展示成表格；
    用到表格组件
    """
    reload_table_signal = QtCore.pyqtSignal(str)

    def __init__(self):
        super(CookBook, self).__init__()
        self.http_util = RequestUtil()
        self.table = PagedTable('cook')
        self.table.edit_triggers_false()      # 设置整表不可编辑
        self.table.row_date.connect(self.get_row_data)
        self.label = QLabel('菜谱名称：')
        self.edit = QLineEdit()
        self.edit.setPlaceholderText('请输入菜谱名称（支持模糊查询）')
        self.edit.setFixedWidth(300)
        self.search = QPushButton('搜索')
        self.search.clicked.connect(self.search_cook)
        self.setWindowTitle("菜谱查询")
        self.init()

        # 连接信号到子控件的方法
        self.reload_table_signal.connect(self.table.init)

    def init(self):
        vbox = QVBoxLayout()

        hbox = QHBoxLayout()

        hbox.addWidget(self.label)
        hbox.addWidget(self.edit)
        hbox.addWidget(self.search)
        hbox.addStretch()
        vbox.addLayout(hbox)
        vbox.addWidget(self.table)
        vbox.addStretch()
        self.setLayout(vbox)
        self.setWindowTitle('菜谱详情')

    def search_cook(self):
        words = self.edit.text()
        if not words:
            return
        result = []
        url = 'http://apis.juhe.cn/fapigx/caipu/query'
        for page in range(1,3):
            post_data = {'key': '5a112d4ccf4d07ea3e0cbc884ccd429c', 'word': words, 'num': '10', 'page': page}
            response_result = self.http_util.post(url=url, data=post_data)
            if response_result['result']:
                result.extend(response_result['result']['list'])
            else:
                break
        if not result:
            QMessageBox.warning(None, "警告", "没查到对应菜谱")
        print(result)
        df = pd.DataFrame(result)
        df = df.set_axis(column_name, axis='columns')

        # 数据转换成表格的使用
        reader = PandasSharedMemory('cook')
        read_dt = reader.read_dataframe()
        if read_dt is None:
            writer = PandasSharedMemory('cook')
            writer.write_dataframe(df)
        else:
            # 读取示例
            modify = PandasSharedMemory('cook')
            modify.modify_dataframe(df)
        self.emit_signal()
        # 调整所有列宽以适应内容
        self.table.resize_columns()

    def emit_signal(self):
        self.reload_table_signal.emit('cook')

    def get_row_data(self, row_data):
        print('row_data', row_data)
        cp = [
                ['菜谱名称', 'QLineEdit', row_data[3], False ],
                ['菜谱类型', 'QLineEdit', row_data[2], False ],
                ['做法', 'QTextEdit', row_data[4], False],
                ['特性', 'QLineEdit', row_data[5], False],
                ['提示', 'QTextEdit', row_data[6], False],
                ['调料', 'QTextEdit', row_data[7], False],
                ['原料', 'QTextEdit', row_data[8], False]
        ]
        form_dialog = FormDialog(cp, 720, 720)
        result = form_dialog.exec_()



